__author__ = 'sdjkx'

import os

from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from libs.Config import Config

BB = QDialogButtonBox
# from PyQt5 import QtCore, QtGui, QtWidgets

class LabelExampleShowDialog(QDialog):

    def __init__(self,parent=None, mydb = None,lable_dict =None, label = "" ):
        super(LabelExampleShowDialog, self).__init__(parent)

        self.mydb = mydb
        self.label = label
        self.labelImg = parent
        self.label_dict = lable_dict
        self.label_img_example = []
        self.labelExampleIndex = 0
        self.queryLabelExampleSql = "select id,file_name from sys_label_img_example where label_id = {0} order by id"
        self.queryLabelExampleImgSql = "select img from sys_label_img_example where id={0}"

        # CatchFilePath = os.getcwd()
        catchLabelImagePath  = os.path.abspath('.')
        catchLabelImagePath = os.path.join(catchLabelImagePath,"Catch/labelImage/")
        self.labelDir = catchLabelImagePath

        self.checkDir()

        self.setObjectName("Dialog")
        self.resize(1153, 772)
        self.label = QLabel(self)
        self.label.setGeometry(QRect(20, 20, 72, 15))
        self.label.setObjectName("label")

        self.listWidget = QListWidget(self)
        self.listWidget.setGeometry(QRect(10, 40, 256, 721))
        self.listWidget.setObjectName("listWidget")
        # self.listWidget.setSelectionMode(QAbstractItemView.ExtendedSelection) #按住CTRL可多选
        self.setListWidget()

        self.imageLabel = QLabel(self)
        self.imageLabel.setGeometry(QRect(280, 40, 861, 691))
        self.imageLabel.setObjectName("ImageLabel")

        self.widget = QWidget(self)
        self.widget.setGeometry(QRect(770, 740, 295, 30))
        self.widget.setObjectName("widget")
        self.horizontalLayout = QHBoxLayout(self.widget)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setObjectName("horizontalLayout")

        self.label_Img_count = QLabel(self.widget)
        self.label_Img_count = QLabel("label_Img_count")
        self.label_Img_count.setText("           0 / 0       ")
        self.horizontalLayout.addWidget(self.label_Img_count)

        self.btnPrev = QPushButton(self.widget)
        self.btnPrev.setObjectName("btnPrev")
        self.horizontalLayout.addWidget(self.btnPrev)
        self.btnNext = QPushButton(self.widget)
        self.btnNext.setObjectName("btnNext")
        self.horizontalLayout.addWidget(self.btnNext)
        self.btnExit = QPushButton(self.widget)
        self.btnExit.setObjectName("btnExit")
        self.horizontalLayout.addWidget(self.btnExit)

        self.btnPrev.clicked.connect(self.prevClick)
        self.btnNext.clicked.connect(self.nextClick)
        self.btnExit.clicked.connect(self.exitClick)
        # self.pushButton.clicked.connect(self.show_urlimage)

        # self.setLayout(self.layout)
        self.setWindowTitle("标签图标")
        self.label.setText( "标签列表")
        self.btnPrev.setText( "上一张")
        self.btnNext.setText( "下一张")
        self.btnExit.setText( "退出")

        # self.retranslateUi(self)
        # QMetaObject.connectSlotsByName(self)


    def setListWidget(self):
        if self.label_dict is not None and len(self.label_dict) > 0:
            for item in self.label_dict.keys():
                self.listWidget.addItem(item)

            self.listWidget.itemClicked.connect(self.listItemClick)
            # self.listWidget.itemDoubleClicked.connect(self.listItemDoubleClick)


    def retranslateUi(self):
        _translate = QCoreApplication.translate
        self.setWindowTitle(_translate("Dialog", "Dialog"))
        self.label.setText(_translate("Dialog", "标签列表"))
        self.btnPrev.setText(_translate("Dialog", "上一张"))
        self.btnNext.setText(_translate("Dialog", "下一张"))
        self.btnExit.setText(_translate("Dialog", "退出"))

    def prevClick(self):
        if len(self.label_img_example) == 0:
            return

        if self.labelExampleIndex == 0:
            return

        self.labelExampleIndex = self.labelExampleIndex - 1
        self.setLabelImage()

    def nextClick(self):
        if len(self.label_img_example) == 0:
            return

        if self.labelExampleIndex + 1 == len(self.label_img_example) :
            return

        self.labelExampleIndex = self.labelExampleIndex + 1
        self.setLabelImage()

    def exitClick(self):
        self.close()

    def listItemClick(self, tQListWidgetItem):
        text_list = self.listWidget.selectedItems()
        key = ""
        if len(text_list) > 0:
            for item in text_list:
                key = item.text()
                break

        if key == "":
            return

        label = self.label_dict[key]

        if label.get_id() != self.labelExampleIndex:
            sql = self.queryLabelExampleSql.format(label.get_id())
            records = self.mydb.executeSql(sql)
            if len(records) == 0:
                QMessageBox.information(self.labelImg, "提示","标签“" + label.get_lableName()+ "”还没有创建标签图例")
                # self.imageLabel.setPixmap(None)
            else:
                self.label_img_example.clear()
                for row in records:
                    self.label_img_example.append((row[0], row[1]))

                self.labelExampleIndex = 0
                self.setLabelImage()

    def setLabelImage(self):
        example = self.label_img_example[self.labelExampleIndex]
        id = example[0]
        filePath = os.path.join(self.labelDir ,example[1])

        if os.path.exists(filePath):
            self.setImage(filePath)
        else:
            self.getImgFromDB(id, filePath)

        self.label_Img_count.setText("           "+str(self.labelExampleIndex + 1)+" / "+str(len(self.label_img_example))+"       ")

    def getImgFromDB(self,id, filePath):
        sql = self.queryLabelExampleImgSql.format(id)
        records = self.mydb.executeSql(sql)
        d = records[0][0]

        f = open(filePath, 'wb')
        f.write(d)
        f.close()

        self.setImage(filePath)

    def setImage(self, filePath):
        # imgName, imgType = QFileDialog.getOpenFileName(self, "打开图片", "", "*.jpg;;*.png;;All Files(*)")
        pix = QPixmap(filePath)
        w = pix.width()
        h = pix.height()
        if w > self.imageLabel.width() or h > self.imageLabel.height():
            if w > h:
                s = self.imageLabel.width()*1.0 / w
                w = self.imageLabel.width()
                h = h * s
            else:
                s = self.imageLabel.height()*1.0 / h
                h = self.imageLabel.height()
                w = w * s

            jpg = pix.scaled(w, h)
            self.imageLabel.setPixmap(jpg)

        else:
            self.imageLabel.setPixmap(pix)

    def checkDir(self):
        if not os.path.exists(self.labelDir):
            os.makedirs(self.labelDir)

    @staticmethod
    def showLabel(parent=None, mydb = None, label_dict= None, label = ""):
        dialog = LabelExampleShowDialog(parent, mydb, label_dict, label)
        dialog.listWidget.selectedIndexes()
        dialog.exec_()